import { Button, Form, Input, InputNumber, Modal, Space, message } from "antd"
import { RedisClient } from "@linksaas-minapp/redis-proxy-api"
import { useEffect, useState } from "react";
import { v4 as uuidv4 } from 'uuid';
import { MinusCircleFilled, PlusCircleFilled } from "@ant-design/icons";
import { getMinAppInfo } from "@linksaas-minapp/api";
import type { RedisServerInfo } from "@linksaas-minapp/api/extra_info";

interface AddrItem {
    id: string;
    addr: string;
}

export interface ConnModalProps {
    onCancel: () => void;
    onOk: (client: RedisClient) => void
}

function ConnModal(props: ConnModalProps) {

    const [name, setName] = useState("");
    const [addrItemList, setAddrItemList] = useState<AddrItem[]>([
        {
            id: uuidv4(),
            addr: "",
        }
    ]);
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [dbId, setDbId] = useState(0);
    const [valid, setValid] = useState(false);

    const checkValid = () => {
        if (name.trim() == "") {
            setValid(false);
            return;
        }
        for (const addrItem of addrItemList) {
            if (addrItem.addr.trim() == "") {
                setValid(false);
                return;
            }
        }
        setValid(true);
    };

    const connectRedis = async () => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const minApp: any = (window as any).minApp;
        const client = new RedisClient(minApp.redisProxyAddr, minApp.redisProxyToken);
        try {
            await client.connect({
                openPostRequest: {
                    token: minApp.redisProxyToken,
                    name: name.trim(),
                    hosts: addrItemList.map(item => item.addr),
                    db: addrItemList.length > 1 ? 0 : dbId,
                    cluster: addrItemList.length > 1,
                    username: username,
                    password: password,
                },
            });
            message.info("连接成功");
            props.onOk(client);
        } catch (e) {
            console.log(e);
            message.error("无法连接redis");
            return;
        }
    };

    useEffect(() => {
        checkValid();
    }, [name, addrItemList]);

    useEffect(() => {
        const minAppInfo = getMinAppInfo();
        if (minAppInfo == undefined) {
            return;
        }
        if (minAppInfo.extraInfo != undefined && minAppInfo.extraInfo.length > 0) {
            const serverInfo = JSON.parse(minAppInfo.extraInfo) as RedisServerInfo;
            setName(minAppInfo.extraInfoName ?? "");
            setAddrItemList((serverInfo.addrs ?? []).map(addr => ({
                id: uuidv4(),
                addr: addr,
            })));
            setUsername(serverInfo.username ?? "");
            setPassword(serverInfo.password ?? "");
            setDbId(serverInfo.dbId ?? 0);
        }
    }, []);

    return (
        <Modal open title="连接Redis"
            okText="连接" okButtonProps={{ disabled: !valid }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                connectRedis();
            }}>
            <Form labelCol={{ span: 5 }}>
                <Form.Item label="名称">
                    <Input value={name} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setName(e.target.value);
                    }} />
                </Form.Item>
                <Form.Item label="地址">
                    {addrItemList.map(item => (
                        <div key={item.id} style={{ display: "flex", marginBottom: "10px" }}>
                            <Input style={{ flex: 1 }} value={item.addr} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                const tmpList = addrItemList.slice();
                                const index = tmpList.findIndex(addrItem => addrItem.id == item.id);
                                if (index != -1) {
                                    tmpList[index].addr = e.target.value;
                                    setAddrItemList(tmpList);
                                }
                            }} />
                            <Space style={{ width: "40px", marginLeft: "20px" }} size="small">
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        const tmpList = addrItemList.slice();
                                        const newList = [] as AddrItem[];
                                        for (const addrItem of tmpList) {
                                            newList.push(addrItem);
                                            if (addrItem.id == item.id) {
                                                newList.push({
                                                    id: uuidv4(),
                                                    addr: "",
                                                });
                                            }
                                        }
                                        setAddrItemList(newList);
                                        checkValid();
                                    }}>
                                    <PlusCircleFilled style={{ fontSize: "20px" }} />
                                </Button>
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} disabled={addrItemList.length <= 1}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setAddrItemList(addrItemList.filter(addrItem => addrItem.id != item.id));
                                    }}>
                                    <MinusCircleFilled style={{ fontSize: "20px" }} />
                                </Button>
                            </Space>
                        </div>
                    ))}
                </Form.Item>
                <Form.Item label="账号">
                    <Input placeholder="redis账号(可选项)" value={username} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setUsername(e.target.value);
                    }} />
                </Form.Item>
                <Form.Item label="密码">
                    <Input.Password placeholder="redis密码(可选项)" value={password} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setPassword(e.target.value);
                    }} />
                </Form.Item>
                <Form.Item label="数据库ID">
                    <InputNumber controls={false} precision={0} min={0} value={dbId} onChange={value => {
                        if (value !== null) {
                            setDbId(value);
                        }
                    }} />
                </Form.Item>
            </Form>
        </Modal>
    );
}

export default ConnModal;